package com.baoyouqun.API.wxPay;

import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;

@Slf4j
public class JSAPIPayService {

    /**
     * 调起支付
     */
    public static PrepayWithRequestPaymentResponse createPayOrder(RSAAutoCertificateConfig config, String orderId, String mchid, String appid,
                                                                  String payName, BigDecimal price, String openid, String notifyUrl) {
        try {
            //初始化商户配置
            JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();

            PrepayRequest request = new PrepayRequest();
            request.setAppid(appid);
            request.setMchid(mchid);
            request.setDescription(payName);
            request.setNotifyUrl(notifyUrl);
            request.setOutTradeNo(orderId);
            //金额
            Integer priceInt = price.multiply(new BigDecimal(100)).intValue();
            Amount amount = new Amount();
            amount.setTotal(priceInt);
            request.setAmount(amount);
            if (StringUtils.isNotBlank(openid)) {
                //客户微信身份标识
                Payer payer = new Payer();
                payer.setOpenid(openid);
                request.setPayer(payer);
            }

            return service.prepayWithRequestPayment(request);
        } catch (HttpException e) {
            log.error(e.getMessage());
            throw new RuntimeException("发送HTTP请求失败");
        } catch (ServiceException e) {
            log.error(e.getMessage());
            throw new RuntimeException("发送HTTP请求成功，返回异常时抛出");
        } catch (MalformedMessageException e) {
            log.error(e.getMessage());
            throw new RuntimeException("解析微信支付应答或回调报文异常");
        }
    }


}